package com.zlzlib.librxoknet.function;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.functions.Function;
import okhttp3.ResponseBody;

/**
 * @Desc: 解析xml的方法
 * @DateTime: 2021/2/22 11:19
 * @Author zlz
 * @Version 1.0
 */
public abstract class BaseSoapXmlFunc implements Function<ResponseBody, String> {

    /**
     * <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
     * <soap:Body>
     * <banyanInterfaceResponse xmlns="http://banyan.doc.web.com/webservice">
     * <return>
     * </return>
     * </banyanInterfaceResponse>
     * </soap:Body>
     * </soap:Envelope>
     */

    //结果节点的名称
    protected abstract String responseKey();

    @Override
    public String apply(@NonNull ResponseBody responseBody) throws Exception {
        // 创建一个xml解析的工厂
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        // 获得xml解析类的引用
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(responseBody.byteStream(), "UTF-8");
        // 获得事件的类型
        int eventType = parser.getEventType();
        String result = "";
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                if (responseKey().equals(parser.getName())) {
                    result = parser.nextText();// 获取该节点的内容
                }
            }
            eventType = parser.next();
        }
        return result;
    }
}
